package javaMSCRM;
import java.awt.BorderLayout;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import com.microsoft.schemas.crm._2006.query.AllColumns;
import com.microsoft.schemas.crm._2006.webservices.Key;
import com.microsoft.schemas.crm._2006.webservices.Lookup;
import com.microsoft.schemas.crm._2006.webservices.Picklist;
import com.microsoft.schemas.crm._2007.webservices.Account;
import com.microsoft.schemas.crm._2007.webservices.CreateDocument;
import com.microsoft.schemas.crm._2007.webservices.CreateResponseDocument;
import com.microsoft.schemas.crm._2007.webservices.DeleteDocument;
import com.microsoft.schemas.crm._2007.webservices.EntityName;
import com.microsoft.schemas.crm._2007.webservices.RetrieveDocument;
import com.microsoft.schemas.crm._2007.webservices.TargetCreateAccount;
import com.microsoft.schemas.crm._2007.webservices.UpdateDocument;
import com.microsoft.schemas.crm._2007.webservices.UpdateResponseDocument;
import com.microsoft.schemas.crm._2007.webservices.CreateDocument.Create;
import com.microsoft.schemas.crm._2007.webservices.CreateResponseDocument.CreateResponse;
import com.microsoft.schemas.crm._2007.webservices.DeleteDocument.Delete;
import com.microsoft.schemas.crm._2007.webservices.RetrieveDocument.Retrieve;
import com.microsoft.schemas.crm._2007.webservices.UpdateDocument.Update;

import net.miginfocom.layout.AC;
import net.miginfocom.layout.LC;
import net.miginfocom.swing.MigLayout;

/**
 * Java MSCRM Account.
 * @author Zoran IVANOV
 * @version     0.1
 */
public class JavaMSCRMAccount extends Form {
	Account record = null;
	JTextField 	JTFName=new JTextField(""),
				JTFPhone=new JTextField(""),
				JTFAccountNumber=new JTextField(""),
				JTFEmail=new JTextField(""),
				JTFStreet1=new JTextField(""),
				JTFPC=new JTextField(""),
				JTFCity=new JTextField(""),
				JTFCountry=new JTextField("");
	JComboBox JCBRelationshipType;
	JButton SaveButton,DeleteButton;
	String[] RelationshipTypeItemsList = new String[]{
			"Competitor",
			"Consultant",
			"Customer",
			"Investor",
			"Partner",
			"Influencer",
			"Press",
			"Prospect",
			"Reseller",
			"Supplier",
			"Vendor",
			"Other"};
	LookupField LFParentAccount,LFPrimaryContact,LFTransactioncurrency;
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;


	/**
	 * @param JavaMSCRM
	 */
	public JavaMSCRMAccount(JavaMSCRM JavaMSCRM) {
		super(JavaMSCRM);
		setTitle("New Account");
		JScrollPane FormScrollPane = new JScrollPane(setupFields());
		FormScrollPane.setBorder(BorderFactory. createEmptyBorder(0,0,0,0));
		add(FormScrollPane, BorderLayout.CENTER);
		pack();
		setVisible(true);
	}
	
	/**
	 * @param JavaMSCRM
	 * @param Id
	 */
	public JavaMSCRMAccount(JavaMSCRM JavaMSCRM, String Id) {
		super(JavaMSCRM, Id);
		try {
	        RetrieveDocument rd = RetrieveDocument.Factory.newInstance();  
	        Retrieve r = Retrieve.Factory.newInstance();	        
	        r.setEntityName(EntityName.ACCOUNT.toString());
	        r.setId(Id);
	        r.setColumnSet(AllColumns.Factory.newInstance());	        
	        rd.setRetrieve(r);
	        record = (Account) JavaMSCRM.stub.Retrieve(rd,  JavaMSCRM.catd, null, null).getRetrieveResponse().getRetrieveResult();
		}  
		catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.toString());
		}		
		setTitle("Account: " + record.getName());
		JScrollPane FormScrollPane = new JScrollPane(setupFields());
		FormScrollPane.setBorder(BorderFactory. createEmptyBorder(0,0,0,0));
		add(FormScrollPane, BorderLayout.CENTER);
		pack();
		setVisible(true);
	}
		
	/**
	 * @return JPanel
	 */
	private JPanel setupFields(){
		LC layC = new LC().wrap();
		AC colC = new AC().align("right", 0).fill(1, 3).grow(100, 1, 3).align("right", 2).gap("15", 1);
		AC rowC = new AC().index(6).gap("15!").align("top").grow(100, 0);	
		JPanel form = new JPanel(new MigLayout(layC, colC, rowC));		
		JPanel formContainer = new JPanel(new MigLayout(layC, colC, rowC));		
		formContainer.add(form, BorderLayout.NORTH);			
		form.setBorder(BorderFactory. createEmptyBorder(0,0,0,0));
		//Create TextFields
		try{JTFName = new JTextField(record.getName());}catch (Exception e) {}
		try{JTFPhone = new JTextField(record.getTelephone1());}catch (Exception e) {}
		try{JTFAccountNumber = new JTextField(record.getAccountnumber());}catch (Exception e) {}
		
		LFParentAccount = new LookupField(JavaMSCRM,EntityName.ACCOUNT.toString());
		try{LFParentAccount.setValue(record.getParentaccountid().getStringValue(), record.getParentaccountid().getName());}catch (Exception e) {}		
		LFPrimaryContact = new LookupField(JavaMSCRM,EntityName.CONTACT.toString());
		try{LFPrimaryContact.setValue(record.getPrimarycontactid().getStringValue(), record.getPrimarycontactid().getName());}catch (Exception e) {}		
		LFTransactioncurrency = new LookupField(JavaMSCRM,EntityName.TRANSACTIONCURRENCY.toString());
		try{LFTransactioncurrency.setValue(record.getTransactioncurrencyid().getStringValue(), record.getTransactioncurrencyid().getName());}catch (Exception e) {}		
			
		JCBRelationshipType = new JavaMSCRMComboBox(RelationshipTypeItemsList, true);
		try{JCBRelationshipType.setSelectedItem(RelationshipTypeItemsList[record.getCustomertypecode().getIntValue()-1]);}catch (Exception e) {}
		try{JTFEmail = new JTextField(record.getEmailaddress1());}catch (Exception e) {}
		try{JTFStreet1 = new JTextField(record.getAddress1Line1());}catch (Exception e) {}
		try{JTFPC = new JTextField(record.getAddress1Postalcode());}catch (Exception e) {}
		try{JTFCity = new JTextField(record.getAddress1City());}catch (Exception e) {}
		try{JTFCountry = new JTextField(record.getAddress1Country());}catch (Exception e) {}

		addSeparator(form, "General");		
		form.add(new JavaMSCRMLabel("Account Name", true));		
		form.add(JTFName, "w 200:100:");
		form.add(new JavaMSCRMLabel("Main Phone", false));
		form.add(JTFPhone, "w 200:100:");		
		form.add(new JavaMSCRMLabel("Account Number", false));
		form.add(JTFAccountNumber, "w 200::");
		form.add(new JavaMSCRMLabel("Parent Account", false));
		form.add(LFParentAccount, "w 200:100:");
		form.add(new JavaMSCRMLabel("Primary Contact", false));
		form.add(LFPrimaryContact, "w 200:100:");
		form.add(new JavaMSCRMLabel("Currency", false));
		form.add(LFTransactioncurrency, "w 200:100:");
		form.add(new JavaMSCRMLabel("Relationship Type", false));
		form.add(JCBRelationshipType, "w 200:100:");
		form.add(new JavaMSCRMLabel("E-mail", false));
		form.add(JTFEmail, "w 200:100:");
		
		addSeparator(form, "Address");
		form.add(new JavaMSCRMLabel("Street 1", false));
		form.add(JTFStreet1, "w 200:100:");
		form.add(new JavaMSCRMLabel("ZIP/Postal Code", false));
		form.add(JTFPC, "w 200:100:");
		form.add(new JavaMSCRMLabel("City", false));
		form.add(JTFCity, "w 200:100:");
		form.add(new JavaMSCRMLabel("Country/Region", false));
		form.add(JTFCountry, "w 200:100:");
		
		return formContainer;
	}

	/* (non-Javadoc)
	 * @see JavaMSCRMForm#createRecord()
	 */
	public void createRecord(){
		String EntityId = "";
		try {
			TargetCreateAccount targetEntity = TargetCreateAccount.Factory.newInstance();
			Account Entity = targetEntity.addNewAccount();
			
			Entity.setName(JTFName.getText());
			Entity.setTelephone1(JTFPhone.getText());
			Entity.setAccountnumber(JTFAccountNumber.getText());
			
			Lookup parentAccountId = Lookup.Factory.newInstance();
			parentAccountId.setStringValue(LFParentAccount.RecordId);
			parentAccountId.setName(LFParentAccount.RecordName);
			Entity.setParentaccountid(parentAccountId);
			
			Lookup PrimaryContactId = Lookup.Factory.newInstance();
			PrimaryContactId.setStringValue(LFPrimaryContact.RecordId);
			PrimaryContactId.setName(LFPrimaryContact.RecordName);
			Entity.setPrimarycontactid(PrimaryContactId);
			
			Lookup TransactioncurrencyId = Lookup.Factory.newInstance();
			TransactioncurrencyId.setStringValue(LFTransactioncurrency.RecordId);
			TransactioncurrencyId.setName(LFTransactioncurrency.RecordName);
			Entity.setTransactioncurrencyid(TransactioncurrencyId);
			
			Picklist ctc = Picklist.Factory.newInstance();
			ctc.setIntValue(JCBRelationshipType.getSelectedIndex());
			Entity.setCustomertypecode(ctc);
			Entity.setEmailaddress1(JTFEmail.getText());
			Entity.setAddress1Line1(JTFStreet1.getText());
			Entity.setAddress1Postalcode(JTFPC.getText());
			Entity.setAddress1City(JTFCity.getText());
			Entity.setAddress1Country(JTFCountry.getText());
						
			CreateDocument cd = CreateDocument.Factory.newInstance();
			Create create = Create.Factory.newInstance();
			create.setEntity(Entity);
			cd.setCreate(create);
		
			CreateResponseDocument crd = JavaMSCRM.stub.Create(cd, JavaMSCRM.catd, null, null);
			CreateResponse cr = crd.getCreateResponse();
			EntityId = cr.getCreateResult();
		}  
		catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.toString());
		}
		
		if(EntityId != ""){
			new Accounts(JavaMSCRM);
			new JavaMSCRMAccount(JavaMSCRM,EntityId);
			dispose();
		}else{
			JOptionPane.showMessageDialog(null, "There was an error while creating the record!");
		}		
	}
	
	/* (non-Javadoc)
	 * @see JavaMSCRMForm#updateRecord()
	 */
	public void updateRecord(){
		try {
			TargetCreateAccount targetEntity = TargetCreateAccount.Factory.newInstance();
			Account Entity = targetEntity.addNewAccount();

			Entity.setName(JTFName.getText());
			Entity.setTelephone1(JTFPhone.getText());
			Entity.setAccountnumber(JTFAccountNumber.getText());
			
			Lookup parentAccountId = Lookup.Factory.newInstance();
			parentAccountId.setStringValue(LFParentAccount.RecordId);
			parentAccountId.setName(LFParentAccount.RecordName);
			Entity.setParentaccountid(parentAccountId);
			
			Lookup PrimaryContactId = Lookup.Factory.newInstance();
			PrimaryContactId.setStringValue(LFPrimaryContact.RecordId);
			PrimaryContactId.setName(LFPrimaryContact.RecordName);
			Entity.setPrimarycontactid(PrimaryContactId);
			
			Lookup TransactioncurrencyId = Lookup.Factory.newInstance();
			TransactioncurrencyId.setStringValue(LFTransactioncurrency.RecordId);
			TransactioncurrencyId.setName(LFTransactioncurrency.RecordName);
			Entity.setTransactioncurrencyid(TransactioncurrencyId);
			
			Picklist ctc = Picklist.Factory.newInstance();
			if(JCBRelationshipType.getSelectedIndex()>0){				
				ctc.setIntValue(JCBRelationshipType.getSelectedIndex());
			}else{
				ctc.setIsNull(true);
			}
			Entity.setCustomertypecode(ctc);
			Entity.setEmailaddress1(JTFEmail.getText());
			Entity.setAddress1Line1(JTFStreet1.getText());
			Entity.setAddress1Postalcode(JTFPC.getText());
			Entity.setAddress1City(JTFCity.getText());
			Entity.setAddress1Country(JTFCountry.getText());
			
			Key id = Key.Factory.newInstance();
			id.setStringValue(this.EntityId);
			Entity.setAccountid(id);
			
			UpdateDocument ud = UpdateDocument.Factory.newInstance();
			Update update = Update.Factory.newInstance();
			update.setEntity(Entity);
			ud.setUpdate(update);
			
			UpdateResponseDocument urd = this.JavaMSCRM.stub.Update(ud, JavaMSCRM.catd, null, null);
			urd.getUpdateResponse();
		}  
		catch (Exception e) {
			String es = e.toString();
			if(es.contains("org.apache")){
				JOptionPane.showMessageDialog(null, "There has been an error while executing the last action!");
			}else{
				JOptionPane.showMessageDialog(null, es);
			}			
		}
		
		new Accounts(JavaMSCRM);
		new JavaMSCRMAccount(this.JavaMSCRM,this.EntityId);
		dispose();
	}
	
	/* (non-Javadoc)
	 * @see JavaMSCRMForm#deleteRecord()
	 */
	public void deleteRecord(){
		((JComponent)getContentPane()).revalidate();
		String msg ="Record succesfuly deleted";
		int deleteConfirmation = JOptionPane.showConfirmDialog(null,
	       		"Are you sure you want to delete this record?",
	       		"Record Deletion Confirmation", 
		        JOptionPane.YES_NO_OPTION);
		if (deleteConfirmation == JOptionPane.YES_OPTION){
			try {
				DeleteDocument dd = DeleteDocument.Factory.newInstance();
				Delete d = Delete.Factory.newInstance();
				d.setId(this.EntityId);
				d.setEntityName(EntityName.ACCOUNT.toString());
				
				dd.setDelete(d);
				
				JavaMSCRM.stub.Delete(dd, JavaMSCRM.catd, null, null);
			}  
			catch (Exception e) {
				msg ="There was a problem while deleting some of the record!";
			}
			
			new Accounts(JavaMSCRM);			
			dispose();
			JOptionPane.showMessageDialog(null, msg);
		}
	}
}
